"use strict";

const db = uniCloud.database();
const trackCollection = db.collection("map-tracks");
const $ = db.command.aggregate;

exports.main = async (event, context) => {
  const { action, data, uniIdToken } = event;

  // 获取用户身份信息
  let userInfo;
  try {
    const uniID = require("uni-id-common");
    const idInstance = uniID.createInstance({ context });
    userInfo = await idInstance.checkToken(uniIdToken);
    if (userInfo.code !== 0) {
      return { code: 401, message: "未授权，请登录后操作" };
    }
  } catch (e) {
    return { code: 502, message: "服务器异常" };
  }

  const userId = userInfo.uid;

  switch (action) {
    // 保存轨迹
    case "saveTrack": {
      try {
        if (!data.locations || data.locations.length < 2) {
          return { code: 400, message: "轨迹数据不完整" };
        }

        // 设置必要数据
        const trackData = {
          ...data,
          user_id: userId,
          date: new Date(),
          create_date: new Date(),
          update_date: new Date(),
        };

        // 如果未设置标题，设置默认标题
        if (!trackData.title) {
          const now = new Date();
          trackData.title = `轨迹 ${now.getFullYear()}-${
            now.getMonth() + 1
          }-${now.getDate()} ${now.getHours()}:${now.getMinutes()}`;
        }

        // 计算其他指标
        if (data.distance && data.duration) {
          trackData.avg_speed = data.distance / data.duration; // 米/秒

          // 计算卡路里消耗 (简单估算，实际应考虑用户体重等)
          // 假设每公里消耗60千卡
          trackData.calories = (data.distance / 1000) * 60;
        }

        const result = await trackCollection.add(trackData);
        return { code: 0, message: "轨迹保存成功", data: { id: result.id } };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "保存轨迹失败" };
      }
    }

    // 获取轨迹列表
    case "getTrackList": {
      try {
        const { page = 1, pageSize = 10 } = data;
        const skip = (page - 1) * pageSize;

        const list = await trackCollection
          .where({ user_id: userId })
          .orderBy("date", "desc")
          .skip(skip)
          .limit(pageSize)
          .get();

        const total = await trackCollection.where({ user_id: userId }).count();

        return {
          code: 0,
          message: "获取轨迹列表成功",
          data: {
            list: list.data,
            pagination: {
              page,
              pageSize,
              total: total.total,
            },
          },
        };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "获取轨迹列表失败" };
      }
    }

    // 获取轨迹详情
    case "getTrackDetail": {
      try {
        const { trackId } = data;
        if (!trackId) {
          return { code: 400, message: "缺少轨迹ID" };
        }

        const result = await trackCollection.doc(trackId).get();
        if (result.data.length === 0) {
          return { code: 404, message: "轨迹不存在" };
        }

        const track = result.data[0];
        // 检查权限
        if (track.user_id !== userId && !track.is_public) {
          return { code: 403, message: "无权查看该轨迹" };
        }

        return { code: 0, message: "获取轨迹详情成功", data: track };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "获取轨迹详情失败" };
      }
    }

    // 更新轨迹
    case "updateTrack": {
      try {
        const { trackId, ...updateData } = data;
        if (!trackId) {
          return { code: 400, message: "缺少轨迹ID" };
        }

        // 检查轨迹是否属于当前用户
        const trackInfo = await trackCollection.doc(trackId).get();
        if (trackInfo.data.length === 0) {
          return { code: 404, message: "轨迹不存在" };
        }

        const track = trackInfo.data[0];
        if (track.user_id !== userId) {
          return { code: 403, message: "无权修改该轨迹" };
        }

        // 设置更新时间
        updateData.update_date = new Date();

        await trackCollection.doc(trackId).update(updateData);
        return { code: 0, message: "更新轨迹成功" };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "更新轨迹失败" };
      }
    }

    // 删除轨迹
    case "deleteTrack": {
      try {
        const { trackId } = data;
        if (!trackId) {
          return { code: 400, message: "缺少轨迹ID" };
        }

        // 检查轨迹是否属于当前用户
        const trackInfo = await trackCollection.doc(trackId).get();
        if (trackInfo.data.length === 0) {
          return { code: 404, message: "轨迹不存在" };
        }

        const track = trackInfo.data[0];
        if (track.user_id !== userId) {
          return { code: 403, message: "无权删除该轨迹" };
        }

        await trackCollection.doc(trackId).remove();
        return { code: 0, message: "删除轨迹成功" };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "删除轨迹失败" };
      }
    }

    // 获取周/月/年统计数据
    case "getStatistics": {
      try {
        const { type = "week" } = data; // 可选值: week, month, year

        const now = new Date();
        let startDate;

        // 根据类型确定统计起始时间
        if (type === "week") {
          // 本周第一天
          const dayOfWeek = now.getDay() || 7; // 转换周日为7
          startDate = new Date(now);
          startDate.setDate(now.getDate() - (dayOfWeek - 1));
          startDate.setHours(0, 0, 0, 0);
        } else if (type === "month") {
          // 本月第一天
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        } else if (type === "year") {
          // 本年第一天
          startDate = new Date(now.getFullYear(), 0, 1);
        }

        // 聚合查询
        const result = await trackCollection
          .aggregate()
          .match({
            user_id: userId,
            date: db.command.gte(startDate),
          })
          .group({
            _id: null,
            total_distance: $.sum("$distance"),
            total_duration: $.sum("$duration"),
            total_calories: $.sum("$calories"),
            count: $.sum(1),
          })
          .end();

        const stats =
          result.data.length > 0
            ? result.data[0]
            : {
                total_distance: 0,
                total_duration: 0,
                total_calories: 0,
                count: 0,
              };

        // 计算平均速度
        const avg_speed =
          stats.total_duration > 0
            ? stats.total_distance / stats.total_duration
            : 0;

        return {
          code: 0,
          message: "获取统计数据成功",
          data: {
            ...stats,
            avg_speed,
          },
        };
      } catch (e) {
        console.error(e);
        return { code: 500, message: "获取统计数据失败" };
      }
    }

    default:
      return { code: 400, message: "无效的操作类型" };
  }
};
